package com.enqualcomm.kids.mvp.voiceschedule;

import android.content.Context;
import android.os.Bundle;

import com.enqualcomm.kids.config.Constants;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;

import java.util.UUID;

import rx.Observable;
import rx.subjects.PublishSubject;


/**
 * Created by yinzhiqun on 2016/3/10.
 * 语音合成
 */
public class SpeechSynthesizerModel implements SynthesizerListener {

    SpeechSynthesizer mTts;
    private final PublishSubject<String> subject;
    String audioPath;

    public SpeechSynthesizerModel(Context context) {
        SpeechUtility.createUtility(context, "appid=56d40e19");
        mTts = SpeechSynthesizer.createSynthesizer(context, null);
        mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");//设置发音人
        mTts.setParameter(SpeechConstant.SPEED, "50");//设置语速,默认50
        mTts.setParameter(SpeechConstant.VOLUME, "80");//设置音量,默认50
        mTts.setParameter(SpeechConstant.PITCH,"50");//设置语调,默认50，数值越大声音越尖
        mTts.setParameter(SpeechConstant.EMOT,"happy");//情感 neutral, happy, sad, angry,默认neutral
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT,"pcm");//保存格式 wav pcm,默认pcm
        mTts.setParameter(SpeechConstant.SAMPLE_RATE,"8000");//采样率,8000,16000
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置云端
        subject = PublishSubject.create();
    }

    public void start(String text){
        if (mTts.isSpeaking()) {//是否正在合成
            mTts.stopSpeaking();
        }
        //3.开始合成,不播放
//        this.audioPath = MyApplication.getInstance().getFilesDir() + "/"+UUID.randomUUID();
        this.audioPath = Constants.TEMP_PATH+"/"+UUID.randomUUID()+".pcm";
        mTts.synthesizeToUri(text,audioPath,this);
    }

    public void destroy(){
        mTts.destroy();
        subject.onCompleted();
    }

    @Override
    public void onSpeakBegin() {
    }

    @Override
    public void onBufferProgress(int i, int i1, int i2, String s) {
    }

    @Override
    public void onSpeakPaused() {
    }

    @Override
    public void onSpeakResumed() {
    }

    @Override
    public void onSpeakProgress(int i, int i1, int i2) {
    }

    @Override
    public void onCompleted(SpeechError speechError) {
        if (speechError==null){
            //合成成功
            subject.onNext(audioPath);
        }else{
            //合成失败
            subject.onNext(null);
        }
    }

    @Override
    public void onEvent(int i, int i1, int i2, Bundle bundle) {
    }

    public Observable<String> onSynthesizerCompleted(){
        return subject.asObservable();
    }
}
